#!/bin/sh
#抽取navinfo_parquet_d006障数据到dwd_predict_slip_pdi表中,单车单故障每天只计算一次，最早出现和最晚出现时间分别为开始，终止时间
CUR_DIR=$(cd "$(dirname "${BASH_SOURCE-$0}")"; pwd)
UP_DIR=$(dirname $(dirname $(dirname "$PWD")))
echo ${UP_DIR}
source ${UP_DIR}/system_env.sh


START_TIME=$(date +%s)
hive_db=${hive_db}

if [ -z "${hive_db}" ];then
  hive_db=dataplatform_trip
else
  hive_db=${hive_db}
fi


if [ -z "$1" ];then
  part_time=$(date -d "1 days ago" +%Y%m%d)
else
  part_time=$1
fi

sql_suffix=$(cat <<EOF
 insert overwrite table ${hive_db}.dwd_predict_slip_pdi partition (day)
   select uid,
          tid,
   	   firsttime,
   	   flip_time,
   	   startingtime,
   	   gear1time,
   	   nvl(round(gear1time/startingtime,1),0) as gear1percent,
   	   gear2time,
   	   nvl(round(gear2time/startingtime,1),0) as gear2percent,
   	   gear3time,
   	   nvl(round(gear3time/startingtime,1),0) as gear3percent,
   	   gear4time,
   	   nvl(round(gear4time/startingtime,1),0) as gear4percent,
   	   gearover4time,
   	   nvl(round(gearover4time/startingtime,1),0) as gearover4percent,
   	   gearr1time,
   	   nvl(round(gearr1time/startingtime,1),0) as gearr1percent,
   	   gearr2time,
   	   nvl(round(gearr2time/startingtime,1),0) as gearr2percent,
   	   day
   from (
   select terminalid as uid,
          terminalid as tid,
       min(case when nvl(split(maintenanceevent2,'_')[10],0) <> 0 then gpsDate else 999999999999 end ) as firsttime,
   	   sum(case when nvl(split(maintenanceevent2,'_')[10],0) <> 0 then 1 else 0 end) as flip_time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[10],0) > 0 then 1 else 0 end) as startingtime,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = 1 then 1 else 0 end ) as gear1time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = 2 then 1 else 0 end ) as gear2time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = 3 then 1 else 0 end ) as gear3time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = 4 then 1 else 0 end ) as gear4time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  > 4 then 1 else 0 end ) as gearover4time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = -1 then 1 else 0 end ) as gearr1time,
   	   sum(case when nvl(split(maintenanceevent3,'_')[8],0)  = -2 then 1 else 0 end ) as gearr2time,
   	   part_time as day
   	    from ${hive_db_source}.navinfo_parquet_d006 where part_time = ${part_time}
   		group by terminalid,part_time ) a

EOF
)

CUR_DIR=$(cd "$(dirname "$0")"; pwd)
hive_config=$(cat  "${CUR_DIR}"/hive.config)
sql="${hive_config}${sql_suffix}"
echo "导入dwc_lc_faultinfo_pdf的SQL为：${sql}"

#执行语句·
hive -e "${sql}"
if [ $? -ne 0 ];then
  echo "导入dwd_predict_slip_pdi失败，耗时$((`date +%s`-START_TIME))秒..."
else
  echo "导入dwd_predict_slip_pdi成功，耗时$((`date +%s`-START_TIME))秒..."
fi